﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace JwtWebApi.Filters
{
    public class ModelValidteFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var modelState = context.ModelState;

            if (!modelState.IsValid)
            {
                context.HttpContext.Response.StatusCode = 400;
                IDictionary<string, IEnumerable<string>> ifno = new Dictionary<string, IEnumerable<string>>();
                foreach (var item in context.ModelState.Keys)
                {
                    var error = context.ModelState[item].Errors;
                    if (error.Any())
                    {
                        var errorDesc = from er in error select er.ErrorMessage;
                        ifno.Add(char.ToLower(item[0]) + item.Substring(1), errorDesc);
                    }
                }

                //context.HttpContext.Response
                context.Result = new BadRequestObjectResult(ifno);
            }
        }
    }
}